<template>
  <div ref="toolbarRef" class="tui-toolbar-wrapper" :class="{ 'tui-toolbar-moving': isMoving }" :style="wrapperStyle" @mousedown="handleMouseDown">
    <!-- 使用单一的Dropdown组件，通过items属性配置菜单 -->
    <tui-dropdown trigger="click" placement="right-start" :items="menuItems" @select="handleSelect">
      <tui-button class="tui-toolbar-button" circle title="工具栏 (按住拖动)">
        <tui-icon icon="tui:menu" />
      </tui-button>
    </tui-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted } from 'vue';
import type { TuiToolbarProps, ToolItem } from './types';

// 定义组件属性
const props = withDefaults(defineProps<TuiToolbarProps>(), {
  position: 'left',
  expandDirection: 'horizontal',
  initiallyExpanded: false,
  width: '40px',
  height: '40px',
  tools: () => [],
  draggable: true
});

// 定义组件引用
const toolbarRef = ref<HTMLElement | null>(null);

// 移动相关状态
const isMoving = ref(false);
const offset = ref({ x: 0, y: 0 });
const position = ref({ x: 0, y: 0 });
const hasCustomPosition = ref(false);

// 计算工具栏包装器样式
const wrapperStyle = computed(() => {
  const style: Record<string, string> = {};

  // 设置宽度和高度
  if (props.width) style.width = props.width;
  if (props.height) style.height = props.height;

  // 设置定位
  style.position = 'fixed';
  style.zIndex = '1000';

  // 如果已经有自定义位置，则使用自定义位置
  if (hasCustomPosition.value) {
    style.left = `${position.value.x}px`;
    style.top = `${position.value.y}px`;
  } else {
    // 根据位置设置定位样式
    switch (props.position) {
      case 'left':
        style.left = '10px';
        style.top = '50%';
        style.transform = 'translateY(-50%)';
        break;
      case 'top':
        style.top = '10px';
        style.left = '50%';
        style.transform = 'translateX(-50%)';
        break;
      case 'right':
        style.right = '10px';
        style.top = '50%';
        style.transform = 'translateY(-50%)';
        break;
      case 'bottom':
        style.bottom = '10px';
        style.left = '50%';
        style.transform = 'translateX(-50%)';
        break;
    }
  }

  // 移动时移除过渡效果，使移动更流畅
  if (isMoving.value) {
    style.transition = 'none';
  }

  return style;
});

// 处理菜单选择事件
const handleSelect = (item: any) => {
  console.log('选择的菜单项:', item);

  // 从items结构中提取工具项信息
  if (item && !item.disabled && item.onClick) {
    item.onClick();
  }
};

// 将tools转换为Dropdown组件需要的items格式
const menuItems = computed(() => {
  // 如果没有提供tools，使用默认菜单项
  if (props.tools.length === 0) {
    return [
      { name: 'home', title: '首页', icon: 'tui:home' },
      { name: 'documents', title: '文档', icon: 'tui:file-text' },
      { name: 'settings', title: '设置', icon: 'tui:settings' },
      { name: 'profile', title: '个人中心', icon: 'tui:user' },
      { name: 'logout', title: '退出登录', icon: 'tui:log-out' }
    ];
  }

  // 转换tools为items格式
  return props.tools.map(tool => {
    const item: any = {
      name: tool.id,
      title: tool.name,
      icon: tool.icon,
      disabled: tool.disabled,
      onClick: tool.onClick
    };

    // 处理子菜单
    if (tool.submenu && tool.submenu.length > 0) {
      item.children = tool.submenu.map((subItem: ToolItem) => ({
        name: subItem.id,
        title: subItem.name,
        icon: subItem.icon,
        disabled: subItem.disabled,
        onClick: subItem.onClick
      }));
    }

    return item;
  });
});

// 鼠标按下事件
const handleMouseDown = (e: MouseEvent) => {
  // 如果禁用拖动，不执行移动逻辑
  if (!props.draggable) return;

  // 只有按下主鼠标按钮（通常是左键）时才触发移动
  if (e.button !== 0 || !toolbarRef.value) return;

  // 阻止默认行为和冒泡，防止文本选择等
  e.preventDefault();
  e.stopPropagation();

  // 获取元素当前位置
  const rect = toolbarRef.value.getBoundingClientRect();

  // 计算鼠标相对于元素左上角的偏移量
  offset.value = {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top
  };

  // 如果是第一次移动，记录当前位置
  if (!hasCustomPosition.value) {
    position.value = {
      x: rect.left,
      y: rect.top
    };
    hasCustomPosition.value = true;
  }

  // 设置移动状态
  isMoving.value = true;

  // 添加全局鼠标事件监听
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

// 鼠标移动事件
const handleMouseMove = (e: MouseEvent) => {
  if (!isMoving.value || !toolbarRef.value) return;

  // 阻止默认行为
  e.preventDefault();

  // 计算新位置（鼠标位置减去偏移量）
  const newX = e.clientX - offset.value.x;
  const newY = e.clientY - offset.value.y;

  // 限制在视口内
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;
  const elementWidth = toolbarRef.value.offsetWidth;
  const elementHeight = toolbarRef.value.offsetHeight;

  // 计算限制后的位置
  const boundedX = Math.max(0, Math.min(newX, viewportWidth - elementWidth));
  const boundedY = Math.max(0, Math.min(newY, viewportHeight - elementHeight));

  // 更新位置
  position.value = { x: boundedX, y: boundedY };
};

// 鼠标释放事件
const handleMouseUp = () => {
  if (!isMoving.value) return;

  // 取消移动状态
  isMoving.value = false;

  // 移除全局鼠标事件监听
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
};

// 组件卸载时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
});
</script>

<style scoped lang="scss">
.tui-toolbar-wrapper {
  background-color: transparent; // 设置为透明背景
  border: none; // 移除边框
  box-shadow: none; // 移除阴影
  transition: all 0.3s ease;
  cursor: move;
  display: flex;
  align-items: center;
  justify-content: center;

  // 禁止文本选择
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;

  // 移动中的样式
  &.tui-toolbar-moving {
    cursor: grabbing !important;
    transition: none !important;
  }
}

.tui-toolbar-button {
  transition: all 0.3s ease;
}
</style>